import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
// import 'package:chewie/chewie.dart';
// import 'package:video_player/video_player.dart';
typedef PageChanged = void Function(int index);

const double _topPadding = 64, _rightPadding = 10, _btnSize = 40, _iconSize = 25;

class PictureOverview extends StatefulWidget {
  final List imageItems; //图片列表
  final int defaultIndex; //默认第几张
  final PageChanged pageChanged; //切换图片回调
  final Axis direction; //图片查看方向
  final Decoration? decoration; //背景设计
  final bool isUrl;

  // ignore: use_key_in_widget_constructors
  const PictureOverview({
    required this.imageItems,
    this.defaultIndex = 0,
    required this.pageChanged,
    this.direction = Axis.horizontal,
    this.decoration,
    this.isUrl = true,
  });

  @override
  _PictureOverviewState createState() => _PictureOverviewState();
}

class _PictureOverviewState extends State<PictureOverview> {
  late int currentIndex;

  @override
  void initState() {
    super.initState();
    currentIndex = widget.defaultIndex;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Stack(
        children: [
          Container(
              margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight, bottom: ScreenUtil().bottomBarHeight),
              child: PhotoViewGallery.builder(
                  scrollPhysics: const BouncingScrollPhysics(),
                  builder: (BuildContext context, int index) {
                    String url = widget.imageItems[index];
                    if (widget.isUrl) {
                      return PhotoViewGalleryPageOptions(
                          minScale: 0.2,
                          maxScale: 2.0,
                          initialScale: PhotoViewComputedScale.contained * 0.8,
                          imageProvider: NetworkImage(widget.imageItems[index]));
                    } else {
                      return PhotoViewGalleryPageOptions(imageProvider: AssetImage(url));
                    }
                  },
                  scrollDirection: widget.direction,
                  itemCount: widget.imageItems.length,
                  backgroundDecoration: const BoxDecoration(color: Colors.black),
                  pageController: PageController(initialPage: widget.defaultIndex),
                  onPageChanged: (index) => setState(() {
                        currentIndex = index;
                        widget.pageChanged(index);
                      }))),
          // Positioned(
          //   bottom: 20,
          //   child: Container(
          //       alignment: Alignment.center,
          //       width: MediaQuery.of(context).size.width,
          //       child: Text("${currentIndex + 1}/${widget.imageItems.length}",
          //           style: TextStyle(
          //             decoration: TextDecoration.none,
          //             color: Colors.white,
          //             fontSize: 16,
          //             fontWeight: FontWeight.w400,
          //             shadows: [
          //               Shadow(color: Colors.black, offset: Offset(1, 1)),
          //             ],
          //           ))),
          // ),
          Positioned(
            //右上角关闭
            top: _topPadding,
            right: _rightPadding,
            child: Container(
              alignment: Alignment.center,
              width: _btnSize,
              height: _btnSize,
              decoration: BoxDecoration(color: Color(0xFF666666), borderRadius: BorderRadius.circular(_btnSize / 2)),
              child: GestureDetector(
                onTap: () {
                  //隐藏预览
                  Navigator.pop(context);
                },
                child: const Icon(
                  Icons.close_rounded,
                  color: Colors.white,
                  size: _iconSize,
                ),
              ),
            ),
          ),
          // Positioned(//数量显示
          //   right: 20,
          //   top: 20,
          //   child: Text(
          //     '${currentIndex + 1}/${widget.imageItems.length}',
          //     style: TextStyle(color: Colors.black),
          //   ),
          // )
        ],
      ),
    );
  }
}

// class PreviewVideoView extends StatefulWidget {
//   final String url;
//   final String? fileName;
//
//   const PreviewVideoView({Key? key, required this.url, this.fileName}) : super(key: key);
//
//   @override
//   State<PreviewVideoView> createState() => _PreViewVideoViewState();
// }
//
// class _PreViewVideoViewState extends State<PreviewVideoView> {
//   ChewieController? chewieController;
//   VideoPlayerController? videoPlayerController;
//   var videoState = false;
//
//   @override
//   void initState() {
//     initController(url: widget.url);
//     super.initState();
//   }
//
//   initController({String? url}) async {
//     // var file = await _downloadVideo(url ?? "");
//     // videoPlayerController = VideoPlayerController.file(file);
//     videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(url ?? ""));
//     videoPlayerController?.initialize().then((value) {
//       chewieController = ChewieController(
//         videoPlayerController: videoPlayerController!,
//         autoPlay: false,
//         looping: false,
//         allowFullScreen: false,
//         // deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp,DeviceOrientation.landscapeLeft]
//       );
//
//       setState(() {
//         videoState = true;
//         SmartDialog.showLoading();
//       });
//     });
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return WillPopScope(
//         child: Material(
//             color: Colors.black,
//             child: Stack(
//               children: [
//                 Container(
//                   alignment: Alignment.center,
//                   child: videoPlayerController != null
//                       ? AspectRatio(
//                           aspectRatio: videoPlayerController?.value.aspectRatio ?? 0,
//                           child: Chewie(controller: chewieController!),
//                         )
//                       : Container(),
//                 ),
//                 Positioned(
//                   //右上角关闭
//                   top: _topPadding,
//                   right: _rightPadding,
//                   child: Container(
//                     alignment: Alignment.centerLeft,
//                     width: _btnSize,
//                     height: _btnSize,
//                     child: GestureDetector(
//                       onTap: () {
//                         //隐藏预览
//                         Navigator.pop(context);
//                         SmartDialog.dismiss();
//                       },
//                       child: const Icon(
//                         Icons.close_rounded,
//                         color: Colors.white,
//                         size: _iconSize,
//                       ),
//                     ),
//                   ),
//                 ),
//               ],
//             )),
//         onWillPop: pop);
//   }
//
//   Future<bool> pop() async {
//     SmartDialog.dismiss();
//     return true;
//   }
//
//   // Future<File> _downloadVideo(String url) async {
//   //   var name = widget.fileName;
//   //   final path = await Utils.faultReportPath();
//   //   final file = File('$path/${name ?? "fault_video.mp4"}');
//   //   if (file.existsSync() == true && name != null) {
//   //     return file;
//   //   }
//   //   XCLoading.showLoading();
//   //   final http.Response response = await http.get(Uri.parse(url));
//   //   final bytes = response.bodyBytes;
//   //   await file.writeAsBytes(bytes);
//   //   return file;
//   // }
//
//   @override
//   void dispose() {
//     chewieController?.dispose();
//     videoPlayerController?.dispose();
//     super.dispose();
//   }
// }
